package com.bloveoa.zkkd.theadPoolConfig;


import com.bloveoa.zkkd.doman.OutTokenModel;
import com.bloveoa.zkkd.repository.OutTokenRepository;
import com.bloveoa.zkkd.util.EthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.web3j.protocol.core.methods.response.EthTransaction;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.Convert;

import java.math.BigInteger;
import java.util.Calendar;
import java.util.List;
import java.util.function.Consumer;

import static com.bloveoa.zkkd.util.EthUtil.getStatus;


/**
 * Created by wuhaochao on 2017/7/25.
 */
@Component
public class AsyncTranscationTask {
    private final OutTokenRepository tokenRepository;

    public AsyncTranscationTask(OutTokenRepository tokenRepository) {
        this.tokenRepository = tokenRepository;
    }
    //myTaskAsynPool即配置线程池的方法名，此处如果不写自定义线程池的方法名，会使用默认的线程池
    @Async("myTaskAsyncPool")
    public void   sendToken() throws InterruptedException {
        List<OutTokenModel> allByFlagDelete = tokenRepository.findAllByFlagDelete(false);
        //获取交易信息是否成功
        allByFlagDelete.forEach(new Consumer<OutTokenModel>() {
            @Override
            public void accept(OutTokenModel tokenModel) {
                String status = getStatus(tokenModel.getTxHash());
                if(status.equals("1")){
                    //成功
                    EthTransaction ethTransaction = EthUtil.getEthTransaction(tokenModel.getTxHash());
                    if(ethTransaction!=null&&ethTransaction.getTransaction()!=null){
                        Transaction transaction = ethTransaction.getTransaction().get();
                        BigInteger value = transaction.getValue();
                        String from = transaction.getFrom();
                        try {
                            TransactionReceipt transactionReceipt = EthUtil.sendErc20Token(from, tokenModel.getOutTokenNum().toPlainString());
                            if(transactionReceipt!=null){
                                tokenModel.setTokenTxHash(transactionReceipt.getTransactionHash())
                                        .setEthStatus(1).setAddress(from).setFlagDelete(true).setInEthNum(Convert.fromWei(String.valueOf(value), Convert.Unit.ETHER))
                                        .setInEthTime(Calendar.getInstance().getTime()).setOutTokenTime(Calendar.getInstance().getTime())
                                ;
                                tokenRepository.save(tokenModel);
                                Thread.sleep(1000);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        });
    }

}
